<template>
	<view>  
		<view class="order_sel">
			<view class="fx-row-sb-c sel_item"  @click="selectAddr()"> 
				<view class="grey3">上门地址</view>
				<view class="fx-row-end-c">
					<view class="fx-col mr26" v-if="orderInfo.addressDefaultId">
						<span>{{orderInfo.addressDefaultName}}  {{orderInfo.addressDefaultPhone}}</span>
						<span style="width: 390rpx;" class="text-beyond">{{orderInfo.addressDefault}}</span>
					</view>
					<view class="mr26" v-else>请选择地址</view>
					<uv-icon name="arrow-right" color="#999" size="16"></uv-icon>
				</view>
			</view>
			<view class="fx-row-sb-c sel_item" @click="suretime">
				<view class="grey3">上门时间</view>
				<view class="fx-row-end-c">
					<span class="mr26">{{time}}</span>
					<uv-icon name="arrow-right" color="#999" size="16"></uv-icon>
				</view>
			</view>
		</view>
		<!-- 服务项目 -->
		<view class="project">
			<view class="fx-row-sb-c" @click="changePors">
				<span class="ft32 bold">服务项目</span>
				<uv-icon name="arrow-right" color="#999" size="16"></uv-icon>
			</view>
			<view class="prolist">
				<view class="fx-row proitem" >
					<view class="proimg">
						<image :src="orderInfo.cover" mode="widthFix" lazy-load></image>
					</view>
					<view class="proinfo">
						<view class="fx-row-sb-c">
							<span class="ft28">{{orderInfo.serviceName}}</span>
							<span class="fx-row-sta ft20"><image src="@/static/picture/time.png" mode="widthFix" style="width:20rpx;height:20rpx;margin-right: 4rpx;" lazy-load></image> <span> {{orderInfo.serviceTime}}分钟</span></span>
						</view>
						<span class="ft20 grey2">{{orderInfo.serviceRecommend}}</span>
						<view class="fx-row-sb-c ft24"> 
							<span class="ft16 red">￥<span style="font-size: 28rpx;">{{conversion(orderInfo.discountPrice)}}</span></span> 
							<uv-number-box style="width: 180rpx;" v-model="projectIndex" :min="1" :max="10" inputWidth='60' :disabledInput="true" @change="snum($event)">
								<template v-slot:minus>
									<view :class="['minus',{'disable':projectIndex=='0'}]"  >
										<uv-icon v-if="projectIndex!='0'" name="minus" size="12" color="#fff"></uv-icon>
										<uv-icon v-else name="minus" size="12" color="#C7C7C7"></uv-icon>
									</view>
								</template>
								<template v-slot:input>
									<text class="input">{{projectIndex}}</text>
								</template>
								<template v-slot:plus>
									<view :class="['plus',{'disable':projectIndex=='10'}]" >
										<uv-icon  v-if="projectIndex!='10'" name="plus" color="#fff" size="12"></uv-icon>
										<uv-icon  v-else name="plus" color="#C7C7C7" size="12"></uv-icon>
									</view>
								</template>
							</uv-number-box>
						</view>
					</view>
				</view>
			</view>
			<view class="fx-col rowtxt ft28">
				<view class="fx-row-sb rowitem" @click="changePer">
					<span>服务人员</span>
					<span class="fx-row-end-c">
						<span class="mr4">{{orderInfo.massagistName}}</span>
						<uv-icon name="arrow-right" color="#999" size="16"></uv-icon>
					</span>
				</view>
				<view class="fx-row-sb rowitem"><span>总价</span><span class="rowri">￥{{conversion(orderInfo.serviceTotalPrice)}}</span></view>
				<view class="fx-row-sb rowitem" @click="selectCoupon">
					<span>优惠券</span>
					<span class="fx-row-end-c">
						<span class="mr4 red" v-if="orderInfo.couponId">￥{{conversion(orderInfo.couponPrice)}}</span>
						<span class="mr4 grey1" v-else></span>
						<uv-icon name="arrow-right" color="#999" size="16"></uv-icon>
					</span>
				</view>
				<view class="fx-row-sb rowitem">  
					<span>出行方式</span>
					<span class="fx-row-end-c">
						<!-- <span class="travel">滴滴</span> -->
						<span class="travel">出租</span>
					</span>
				</view>
				<view class="travel_tip">往返共{{orderInfo.dist}}公里，{{ valuation.distance }}公里以内{{ valuation.price }}元，超出部分{{ valuation.incrementPrice }}元/公里。</view>
				<view class="fx-row-sb rowitem"><span>出行费用</span><span class="grey2 rowri">￥{{conversion(orderInfo.travelPrice)}}</span></view> 
			</view>
		</view>
		 <view class="project">
			 <textarea class="remark" v-model="remards"  placeholder="请提前告知特殊情况（选填）" maxlength='128'/>
		 </view>
		 <view class="project"> 
				<view class="fx-row-sb-c" >
					<view class="fx-row-sta">
						<image style="width: 28rpx;height: 20rpx;" src="@/static/picture/qianbao.png" mode="widthFix" lazy-load></image>
						<view class="account">
							<view class="ft28">SPA钱包账户</view>
							<view class="mt6 ft24 grey1">温馨提示：团购券不得与优惠券同时使用</view>
						</view>
					</view> 
					<view v-if="!orderInfo.hasCoupon" style="font-size: 22rpx">余额不足</view>
					<view v-else class="check" @click="selectAccount">
						<image v-if="!isAccount" style="width: 28rpx;height: 28rpx" src="@/static/icons/check.png" mode="widthFix"></image>
						<image v-else style="width: 28rpx;height: 28rpx" src="@/static/icons/checked.png" mode="widthFix"></image>
					</view>
				</view> 
		 </view>
		 <view class="project">
			 <view class="fx-row-sb-c"  >
			 	<view class="fx-row-sta">
			 		<image style="width: 30rpx;height: 22rpx;" src="@/static/picture/weixin.png" mode="widthFix" lazy-load></image>
			 		<view class="account">
			 			<view class="ft28">微信支付</view> 
			 		</view>
			 	</view> 
			 	<view class="check"> 
			 		<image style="width: 28rpx;height: 28rpx" src="@/static/icons/checked.png" mode="widthFix"></image>
			 	</view>
			 </view>  
		 </view>
		 <!-- 预约时间 -->
		 
		 <!-- <pickerTime ref="time" :times="list"  ></pickerTime> -->
		 <hTimeAlert
				 title="选择预约时间"  
				 :rangeList='list'
				 :isShow="isShow"
				 :maskHide="maskHide"
				 :rangeType="rangeType"
				 :closeBtn="closeBtn"
				 @closeAlert="handelClose"
		 ></hTimeAlert>
		 <!-- 优惠券 -->
		 <uv-popup mode='bottom'  zIndex='991' round="12" duration='300' closeable ref="popup" >
			<coupon ref="cou" :list="coutab" :usableList="usableList" :noList='noList' :couponOnlyId="couponOnlyId" @selectCuopon='couChange'></coupon>
		 </uv-popup>
		 <!-- 更换服务项目 -->
		 <uv-popup mode='bottom'  zIndex='991' round="12" duration='300' closeable ref="service" >
				<projects ref="pro" :tabindex='serviceIndex' :projectInfo='projectInfo' :serviceList="serviceList"  @placeOrder='cproject' ></projects>
		 </uv-popup>
		<!-- 底部栏 -->  
		<block  >
			<view style="width: 100%;height: 115rpx;"></view>
			<view class="fx-row-sb-c orderbtn ">   
				<span>合计：<span class="red">￥</span> <span  class="ft40 red">	{{conversion(orderInfo.totalPrice)}}</span></span>
				<span  class="obtn3" @click="surePay">立即支付</span>    
			</view>
		</block> 
		<!-- 引导关注模态框 -->
		<!-- <uv-modal ref="modal" content="是否关注公众号授权消息订阅功能？" showConfirmButton showCancelButton @confirm='subscription' @cancel='cancel'></uv-modal> -->
	</view>
</template>

<script>
	import badgeMix from '@/common/mixins.js'  
	import hTimeAlert from "@/components/h-time-alert.vue";
	import coupon from "@/components/coupon.vue"
	import projects from "@/components/change-project.vue"
	import config from '@/config.js' 
	import { precontractOrder,massagistDetails,addOrder,orderCoupon,massagistTime,orderPay,geturl,wxConcerned} from '@/utils/api.js'  
	export default {
		mixins: [badgeMix],
		components: {hTimeAlert,coupon,projects},
		data() {
			return {
				timeData: {},
				countTime:'',
				orderState:'0',  //0 待支付   1已超时  2进行中   3已完成  4已取消  
				escReason:'',
				projectIndex:'1',
				radiolist: [  //支付方式
					{
						name: '微信支付',
						disabled: true
					},
				],
				radiovalue: '微信支付',
				list:[],
				isShow: false, //预约时间
				maskHide: false,
				closeBtn: true,
				rangeType: false,
        valuation: {
          distance: 0, //	起步里程
          price: 0 , //	起步价
          incrementPrice: 0, //	每公里加价
        },
				time:'请选择',  //技师预约时间
				// coutab:[{'name':'可用优惠券',badge: { value:5 ,},'num':'5'},{'name':'不可用优惠券','num':'5'}],
				coutab:[{'name':'可用优惠券','num':'5'},{'name':'不可用优惠券','num':'5'}],
				usableList:[],  //可使用优惠券
				noList:[],  //不可使用优惠券
 				serviceList:[], // 技师可服务项目列表
				projectInfo:{}, //项目内容
				serviceIndex:'',  //服务项目下标
				orderId:{
					'serviceId':'',//项目id
					'serviceQuantity':'',//项目数量
					'massagistId':'',//技师id
					'addressId':'',//地址id
					'couponId':'',//优惠券id
				},
				orderInfo:{}, //预约返回订单信息
				remards:'',//备注内容 
				source:'' , //来源小程序 公众号
				orderPayId:'', //待支付订单id
				isBack:true, //该订单是否已经生成订单
				couponOnlyId:'', //优惠券唯一标识
				osName:'', //机型系统名称  ios、android 
				isAccount:false
			};
		},
		onLoad(option) {  
			this.orderId.serviceId = option.pid
			this.orderId.serviceQuantity = option.num
			this.orderId.massagistId = option.mid
			this.getOrderinfo();
			// this.isBack = true
		},  		 
		onShow() {  
			// this.getOrderinfo(); 
		},
		methods: {  
			// orderPayBack(con){ 
			// 	return uni.reLaunch({
			// 		url:'/pages/index/index'
			// 	})  
			// }, 
			// 确定订阅
			subscription(){
				this.$refs.modal.close();
				this.goWechatUrl()
			},
			cancel(){
				this.orderPay()
				this.$refs.modal.close();  
			},
			// 预约订单接口
			getOrderinfo(){
				uni.showLoading({
					title:'加载中'
				})
				const datas = {
					'serviceId':this.orderId.serviceId,
					'serviceQuantity':this.orderId.serviceQuantity,
					'massagistId':this.orderId.massagistId,
					'addressId':this.orderId.addressId,
					'couponId':this.orderId.couponId,
					'useCoupon':this.isAccount
				}
				 precontractOrder(datas).then((res) => {
					uni.hideLoading()
					if(res.code == '200'){   
						res.result.dist = parseFloat(res.result.dist).toFixed(2)
						this.orderInfo = res.result
            for (const valuationKey in this.valuation) {
              this.valuation[valuationKey] = this.auxiliary(this.valuation[valuationKey], res.result[valuationKey], valuationKey)
            }
						this.projectIndex = res.result.serviceQuantity
						this.orderId.addressId = res.result.addressDefaultId
						if(!res.result.hasCoupon){
							this.isAccount = false
						}
					}else{
						uni.showToast({
							title:res.message,
							icon:'none'
						})
						setTimeout(()=>{
							uni.navigateBack()
						},1000)
					}
				}) 
			},

      auxiliary (source, target, Key) {
        if (typeof source === 'number') {
          if (Key === 'distance') {
            return target ?? 0
          }
          return target ? target / 100  : 0
        }
        return target ?? ''
      },
			// 选择上门时间
			async suretime(){  
				await massagistTime({"massagistId":this.orderId.massagistId}).then((res) => { 
					if(res.code == '200'){
						res.result.forEach((item,index)=>{
							item['checked'] = false
						})
						this.list = res.result 
					}
				}) 
				// this.$refs.time.show();
				this.isShow = true;
			}, 
			// 选择优惠券列表
			selectCoupon(){  
				if(this.isAccount){
					return uni.showToast({
						icon:'none',
						title:'团购券不能与优惠券同时使用！'
					})
				}
				this.usableList = []
				this.noList = [] 
				orderCoupon({'serviceId':this.orderId.serviceId,'serviceCount':this.orderId.serviceQuantity}).then(async(res) => { 
					if(res.code == '200'){ 
						await res.result.forEach((item,index)=>{  
							item.rmb =  this.conversion(item.rmb).split(".")[0]
							item.overflow =  this.conversion(item.overflow).split(".")[0]
							item.beginDate = item.beginDate.replace(/-/g,'.')
							item.endDate = item.endDate.replace(/-/g,'.')
							if(item.isUsable == 0){
								this.usableList.push(item) 
							}else if(item.isUsable == 1){
								this.noList.push(item) 
							}
						}) 
						this.coutab[0].name = `可使用优惠券(${this.usableList.length})`
						this.coutab[1].name = `不可使用优惠券(${this.noList.length})`  
					}
				}) 
				this.$refs.popup.open('bottom');
				// this.$refs.cou.show();
			},
			// 更换服务项目
			changePors(){
				// 获取技师可以服务的项目  this.orderId.serviceId 项目id
				const datas = {
					"lon":uni.getStorageSync('longitude'),  //经度
					"lat":uni.getStorageSync('latitude'),  //纬度  
					'massagistId':this.orderId.massagistId,
					// #ifdef MP-WEIXIN
					"source" : 'WeChatMini',
					"version" : config.appInfo.version
					// #endif
				}
				massagistDetails(datas).then((res) => {
					if(res.code == '200'){
						res.result.serviceList.forEach(async(item,indexs)=>{
							item.discountPrice =  this.conversion(item.discountPrice).split(".")[0]
							item.price =  this.conversion(item.price).split(".")[0]   
						}) 
						this.serviceList = res.result.serviceList 
						this.serviceList.forEach((item,index)=>{
							if(item.id == this.orderId.serviceId){
								this.serviceIndex = index
								this.projectInfo = item
							}
						})
					}
				}) 
				this.$refs.service.open('bottom');
			},
			// 更换服务项目回调
			cproject(pid,num){
				this.$refs.service.close('bottom');
				this.orderId.serviceId = pid
				this.orderId.serviceQuantity = num
				this.orderId.couponId = '' 
				this.couponOnlyId = ''
				this.getOrderinfo();
			},
			// 更换服务人员
			changePer(){ 
				uni.navigateTo({
					url:`/pages/order/selectPerson?id=${this.orderId.serviceId}`
				}) 
			}, 
			// 更换人员回调
			async changePerson(id){
				  this.orderId.massagistId = await id
					this.time = '请选择时间'
				 await this.getOrderinfo();  
			},
			// 选择地址
			selectAddr(){
				uni.navigateTo({
					url:`/pages/user/address?state=select&id=${this.orderId.addressId}`
				})
			},
			// 选择钱包账户
			selectAccount(){
				this.isAccount = !this.isAccount
				if(this.isAccount){
					this.orderId.couponId = ''
					this.couponOnlyId = ''
				}
				this.getOrderinfo();
			},
			// 更换地址回调
			changeAddr(id){
				this.orderId.addressId = id
				this.getOrderinfo();
			}, 
			//选择优惠券回调
			couChange(id,couponOnlyId){ 
				this.orderId.couponId = id
				this.couponOnlyId = couponOnlyId
				this.getOrderinfo();
				this.$refs.popup.close('bottom');
			},
			//立即支付 
			async surePay(){ 
				var _this = this
				if(!this.orderId.addressId){
					return uni.showToast({
						title:'请选择地址后在下单！',
						icon:'none'
					})
				}
				if(this.time=='请选择' || !this.time){
					return uni.showToast({
						title:'请选择要预约的时间！',
						icon:'none'
					})
				}
				if(!uni.getStorageSync('OPENID') || uni.getStorageSync('OPENID').type == 'undefined'){
					await this.$u.wxOauth1()   
				}
				// #ifdef MP-WEIXIN
				// 小程序支付拉起一次性订阅
				await this.subScribeMsg().then(result => {
					// 处理操作成功的情况，result为操作成功的结果
				}).catch(error => {
					// 处理操作失败的情况，error为发生的错误
				});  
				await this.orderPay()
				// #endif 
				
				// #ifdef H5
				this.orderPay()  
				// #endif  
			},
			//生成订单
			orderPay(){
				var _this = this;
				uni.showLoading({
					title:'加载中'
				}) 
				// #ifdef MP-WEIXIN
				this.source = 'WeChatMini'
				// #endif 
				// #ifdef H5 
				this.source = 'WeChat'
				// #endif
				const datas = {
					"serviceId": this.orderId.serviceId,  //项目id 
					"serviceQuantity": this.orderId.serviceQuantity,  //项目数量
					"massagistId": this.orderId.massagistId,  //技师id
					"travelType": "出租",  //出行方式  false
					"addressId": this.orderId.addressId,  // 地址id
					"appointTime": this.time + ':00',  //上门时间
					"couponId": this.orderId.couponId,   //优惠券id  false
					"remark": this.remards,   //备注
					"priceType": "微信支付"   ,//支付方式 false
					"openId":uni.getStorageSync('OPENID') ,
					"source":this.source,  //微信小程序：WeChatMini，微信公众号：WeChat） 
					'useCoupon':this.isAccount
				}
				addOrder(datas).then((res) => {
					this.isBack = false
					uni.hideLoading()  
					if(res.code == '200'){  
						this.orderPayId = res.result.id 
						orderPay({"orderId":res.result.id,"openId":uni.getStorageSync('OPENID'),"source":this.source}).then((paydata)=>{ 
							if(paydata.code == '200'){
								// #ifdef MP-WEIXIN
								this.mpPay(paydata.result)  
								// #endif 
								// #ifdef H5     
								WeixinJSBridge.invoke('getBrandWCPayRequest', {
										"appId": paydata.result.appId,     //公众号ID，由商户传入     
										"timeStamp": paydata.result.timeStamp,     //时间戳，自1970年以来的秒数     
										"nonceStr": paydata.result.nonceStr,        //随机串     
										"package": paydata.result.packAge, 
										"signType": paydata.result.signType,    //微信签名方式：     
										"paySign":  paydata.result.paySign,  //微信签名 
								},
								function(res){
									if (res.err_msg == 'get_brand_wcpay_request:cancel') {
										uni.showToast({title:'支付失败！',icon:'none'})
										setTimeout(()=>{
											uni.redirectTo({
												url:'/pages/order/orderDetails?state=info&id=' + _this.orderPayId
											})
										},1000) 
									}
									if (res.err_msg == 'get_brand_wcpay_request:ok') {
										uni.showToast({title:'支付成功！'}) 
										setTimeout(()=>{
											// uni.redirectTo({
											// 	url:'/pages/order/orderDetails?state=info&id=' + _this.orderPayId
											// })
											uni.redirectTo({
												url:'/pages/order/paySuccess?state=info&id=' + _this.orderPayId
											})
										},1000)  
									}
									// 支付失败
									if (res.err_msg == "get_brand_wcpay_request:fail") {
										uni.showToast({title:'支付失败！',icon:'none'})
									}
									/**
									 * 其它
									 * 1、请检查预支付会话标识prepay_id是否已失效
									 * 2、请求的appid与下单接口的appid是否一致
									 * */
									if (res.err_msg == "调用支付JSAPI缺少参数：total_fee") {
													
									} 
								})  
								// #endif
							}else if(paydata.code == '00007'){
								uni.showToast({title:paydata.message,icon:'none'})
							}
							
						}) 
					}else{
						uni.showToast({title:res.message,icon:'none'})
					}
				}) 
			},
			// 小程序支付
			mpPay(paydata){
				var {orderPayId} = this
				uni.requestPayment({
					provider:'wxpay',  
					timeStamp:paydata.timeStamp,
					nonceStr:paydata.nonceStr,
					package: paydata.packAge,
					signType:paydata.signType,
					paySign:paydata.paySign,
					success: function (res) {
						uni.showToast({
							title:'支付成功！'
						})
						setTimeout(()=>{
							uni.redirectTo({
								url:'/pages/order/orderDetails?state=info&id=' + orderPayId
							})
						},1000)
					},
					fail: function (err) { 
						uni.showToast({
							title:'支付失败！',
							icon:'none'
						})
						setTimeout(()=>{
							uni.redirectTo({
								url:'/pages/order/orderDetails?state=info&id=' + orderPayId
							})
						},1000)
					}
				})
			},
			// 项目数量改变
			snum(e){ 
				this.orderId.serviceQuantity = e.value 
				this.orderId.couponId = '' 
				this.couponOnlyId = ''
				this.getOrderinfo();
			},
			handelClose(_data){
				this.time = _data.date
				this.isShow = false
			},
		}
	}
</script>

<style lang="scss">
	page{
		background-color: #F8F8F8;
	}  
	.order_sel{
		width:658rpx;
		margin: 16rpx 12rpx;
		padding:20rpx 34rpx;
		background-color:  #fff;
		border-radius: 12rpx;
		.sel_item{
			padding: 18rpx 0;
			font-size: 28rpx;
		}
	}
	.project{
		width:658rpx;
		margin: 16rpx 12rpx;
		padding:20rpx 34rpx;
		background-color:  #fff;
		border-radius: 12rpx;
		.prolist{
			padding: 24rpx 0 16rpx 0;
			border-bottom: 1rpx solid #e6e6e6;
			.proitem{
				margin-bottom: 16rpx;
				.proimg{
					width: 160rpx;
					height: 126rpx;
					margin-right: 24rpx;
					border-radius: 10rpx;
					overflow: hidden;
					image{
						width: 100%;
					}
				}
				.proinfo{
					width:510rpx ;
				}
			}
		}
		.rowtxt{
			margin-top: 20rpx;
			.rowitem{
				padding: 12rpx 0;
				.rowri{
					width:440rpx ;
					text-align: right;
				}
				.travel{
					margin-left:8rpx ;
					padding: 6rpx 22rpx;
					font-size: 24rpx;
					color: #999;
					border: 1rpx solid #999;
				}
			}
			.travel_tip{
				font-size: 18rpx; 
				font-weight: 500;
				color: #A3A3A3;
				line-height: 24rpx;
			}
		}
		.remark{ 
			width: 598rpx;
			height: 130rpx;
			padding: 30rpx;
			font-size: 28rpx;
			background-color:  #F9FAF9; 
			border-radius: 12rpx;
		}
		.account{
			margin-left: 12rpx;
		}
	}
	
	.orderbtn{
		position: fixed;
		bottom: 0;
		left: 0;
		width: 700rpx;
		height: 115rpx;
		padding: 0 25rpx;
		background-color: #fff;
		border-top: 1rpx solid #f9f9f9;
		font-size: 26rpx; 
		.obtn3{
			margin-left: 20rpx;
			padding:18rpx 62rpx ;
			border-radius: 38rpx;
			background-color: $uni-main;
			color: #fff;
			font-size: 28rpx;
		}
	}
	.uv-radio{
		width: 610rpx;
	}
	 
</style>
